<template>
    <div id="muke-right">
        <div id="muke-right-content">
            <!-- 搜索 start -->
            <div class="input-control search-box search-box-circle has-icon-left has-icon-right" id="searchboxMuke">
                <input @change="searchFile(filename)" v-model="filename" id="inputSearchExample1" type="search" class="form-control search-input" placeholder="搜索文件">
                <label for="inputSearchExample1" class="input-control-icon-left search-icon"><i class="icon icon-search"></i></label>
                <a @click="clearSearch" href="#" class="input-control-icon-right search-clear-btn">
                    <i class="icon icon-remove"></i>
                </a>
            </div>
            <!-- 搜索 end -->
            
            <!-- 文件操作 start -->
            <div id="muke-file-edit">
                <div class="muke-file-edit-left">
                    <span id="muke-back-folder" @click="backFolder"></span>
                    <span id="muke-file-title">全部文件</span>
                </div>
                
                <!-- 上传按钮 -->
                <div class="muke-file-edit-block">
                    <el-dropdown @command="handleCommand">
                        <el-button type="primary" size="medium" icon="el-icon-upload">
                            上传<i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="file">文件</el-dropdown-item>
                            <el-dropdown-item command="folder">文件夹</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </div>
                <!-- 新建文件夹 -->
                <div class="muke-file-edit-block">
                    <el-row>
                        <el-button size="medium" icon="el-icon-folder-add" plain @click="newFolder()">新建文件夹</el-button>
                    </el-row>
                </div>
                
                <!-- 清除浮动 -->
                <div style="clear: both;"></div>
                <div id="muke-file-count">共 {{files.length}} 个文件</div>
                <div id="muke-file-count" v-show="checkedFiles.length>0">，已选 {{checkedFiles.length}} 个文件</div>
                <!-- 操作文件按钮 -->
                <div id="muke-file-count" v-show="checkedFiles.length>0">
                    <el-row>
                        <el-button size="small" icon="el-icon-right" round @click="openMove(checkedFiles)">移动</el-button>
                        <el-button size="small" icon="el-icon-delete" round @click="deleteCheckedFiles(checkedFiles)">删除</el-button>
                        <el-button size="small" icon="el-icon-share" round  @click="drawer = true">分享</el-button>
                        <el-button size="small" icon="el-icon-circle-plus-outline" round disabled>复制</el-button>
                        <el-button size="small" icon="el-icon-download" round disabled>下载</el-button>
                        <!-- <el-button size="mini" round>超小按钮</el-button> -->
                    </el-row>
                    
                </div>
                <div id="muke-file-show-icon">
                    <div class="muke-file-show" @click="showListStyle()">
                        <listIcon id="list-icon" ></listIcon>    
                    </div>    
                    <div class="muke-file-show" @click="showGridStyle()">
                        <gridIcon id="list-icon" ></gridIcon>    
                    </div>
                    
                </div>
                
            </div>
            <!-- 文件操作 end -->
            <hr/>
            <!-- 文件显示 start -->
            <div v-show="!isShow" id="muke-filelist-header">
                <div id="header-checkbox">
                    <el-checkbox  :checked="checkAll" :disabled="files.length===0" v-model="checkAll" @change="handleCheckAllChange"></el-checkbox>
                </div>
                <div id="header-name" >
                    <span>文件名</span>
                </div>
                <div id="header-size">
                    <span>文件大小</span>
                </div>
                <!-- 创建时间 -->
                <div id="header-date">
                    <span>更新时间</span>
                </div>
                <div style="clear:both;"></div>
            </div>
            <!-- 文件列表显示 -->
            <div id="muke-file-content" v-loading="loading">
                <!-- 文件网格 -->
                <div v-show="isShow">
                    <el-checkbox-group v-model="checkedFiles" @change="handleCheckedFilesChange">
                        <div  v-for="(file,index) in files" :key="index">
                            <el-checkbox style="float:left;" :label="file" ><span></span></el-checkbox>
                            <mukeFileGrid :file='file' :index='index' />
                        </div>
                    </el-checkbox-group>
                </div>
                <!-- 文件列表 -->
                <div v-show="!isShow">
                    <el-checkbox-group v-model="checkedFiles" @change="handleCheckedFilesChange">
                        <div v-for="(file,index) in files" :key="index">
                            <el-checkbox style="float:left;margin-top:20px" :label='file'><span></span> </el-checkbox>
                            <mukeFileList :file='file' :index='index' @handleChildrenData='handleChildrenData'/>
                        </div> 
                    </el-checkbox-group>
                    <div style="line-height:30px;text-align:center;" v-show="files.length===0">
                        <span>暂无数据</span>
                    </div>
                </div>
                
                
            </div>
            <!-- 文件显示 end -->
        </div>

        <!-- 抽屉 显示分享文件页面-->
        <el-drawer
            title="分享文件"
            :visible.sync="drawer"
            :direction="direction"
            :before-close="handleClose">
            <div class="drawer-content">
                <el-form :model="share" :rules="rules" ref="share">
                    <el-form-item prop="name" required label="分享名称" :label-width="formLabelWidth">
                        <el-input v-model="share.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item prop="validTime" required label="有效期" :label-width="formLabelWidth">
                        <el-select v-model="share.validTime" placeholder="请选择有效期">
                            <el-option label="7天" value="7" selected='selected'></el-option>
                            <el-option label="1月" value="30"></el-option>
                            <el-option label="永久" value="-1"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div class="drawer-footer">
                    <el-button @click="cancelShare">取 消</el-button>
                    <el-button type="primary" @click="createShare('share')" :loading="createLoading">{{ createLoading ? '创建中 ...' : '创建链接' }}</el-button>
                </div>
            </div>
        </el-drawer>

        <!-- 文件分享对话框 -->
        <el-dialog title="分享链接" :visible.sync="dialogFormVisible" width="43%">
            <el-form :model="shareUrl">
                <el-form-item label="链接" :label-width="formLabelWidth">
                    <el-input id="share-url" v-model="shareUrl.url" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="提取码" :label-width="formLabelWidth" style="width:160px">
                    <el-input id="share-code" v-model="shareUrl.code" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">关闭</el-button>
                <el-button type="primary" @click="copyUrlAndCode">复制链接及提取码</el-button>
            </div>
        </el-dialog>

        <!-- 移动文件对话框 -->
        <el-dialog
            title="选择保存路径"
            :visible.sync="moveVisible"
            width="30%"
            :before-close="clearTree"
            :close-on-click-modal="false">
            
            <div id='file-tree'>
                <el-tree
                    :data="data"
                    :load="loadNode"
                    :lazy="true"
                    :highlight-current="true"
                    accordion
                    @node-click="selectNode">
                    <span class="custom-tree-node" slot-scope="{ node }">
                        <span>
                            <i :class="icon2"></i> {{ node.label }}
                        </span>              
                    </span>
                </el-tree>
            </div>
            <p v-if="nodeSelect">当前选中的文件夹 : 
                <span style="color:red;">{{selectedFolderName}}</span> 
            </p>
            <span slot="footer" class="dialog-footer">
                <el-button @click="clearTree">关 闭</el-button>
                <el-button type="primary" :loading="loading"
                     @click="saveMoveFile">{{loading ? '保 存 中':'保 存'}}</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
    import mukeFileGrid from "./mukeFileGrid";
    import mukeFileList from './mukeFileList';
    import listIcon from '../icons/listIcon';
    import gridIcon from '../icons/gridIcon';
    import util from '../../utils/util';
    import EventBus from '../../utils/event-bus';
    export default {
        components:{
            mukeFileGrid,mukeFileList,
            listIcon,gridIcon
        },
        mounted: function(){
    		// 初始化数据
            this.queryAllFiles();
            // j接收事件
            EventBus.$on('loadFileList',(obj)=>{
                console.log('on',obj);
                util.dataConvert(this.files,obj);
            });
            // 清空选中的文件数据
            EventBus.$on('clearSelectFiles',(obj) => {
                this.checkedFiles = [];
                this.checkAll = false;
            }); 
        },
        
        methods: {
            // 复制链接及提取码
            copyUrlAndCode(){
                // 获取分享链接及提取码
                let url = document.getElementById('share-url').value;
                let code = document.getElementById('share-code').value;
                var textarea = document.createElement('textarea');
                textarea.value = `链接：${url}\n
                                提取码：${code}`;
                document.body.appendChild(textarea);
                textarea.select(); // 选择对象
                document.execCommand("Copy"); // 执行浏览器复制命令
                textarea.className = 'textarea';
                textarea.style.display='none';
                this.$message({
                    message: '链接复制成功',
                    type: 'success'
                });

            },
            handleClose(done){
                done();
            },
            cancelShare(){
                this.drawer = false;
            },
            openShareUrl(){
                this.dialogFormVisible = true;
            },
            // 创建分享链接
            createShare(share){
                this.createLoading = true;
                this.$refs[share].validate((valid) => {
                    if (valid) {
                        // 打开生成链接对话框
                        this.openShareUrl();
                        this.drawer = false;
                        let checked = [];
                        for (let file of this.checkedFiles) {
                            checked.push({
                                id:file.id,
                                type:file.type
                            });
                        }
                        let shareDate = this.$refs[share].model;
                        // 发起http请求，获取分享链接及提取码信息
                        this.$axios.post(util.API_HOST+"/file/share/create",{
                            fileListJson:JSON.stringify(checked),
                            shareName:shareDate.name,
                            validTime:shareDate.validTime
                        }).then(response => {
                            let result = response.data;
                            if (result.code === 200){
                                this.$notify.success({
                                    title:result.code,
                                    message:'创建分享链接成功'
                                });
                                this.shareUrl.url = util.WEB_HOST+result.data.url;
                                this.shareUrl.code = result.data.code;
                            }
                            this.createLoading = false;
                        }).catch(err => {
                            this.$notify.error({
                                title:'创建分享链接出错啦',
                                message:err.message
                            })
                            this.createLoading = false;
                        });


                    } else {
                        return false;
                    }
                })
            },
            // 清空文件搜索框内容
            clearSearch(){
                this.filename = '';
            },
            // 搜索文件
            searchFile(filename){
                this.loading = true;
                if(filename.trim() === '') return;
                this.$axios.post(util.API_HOST+'/file/file/search/files',
                {
                    filename
                }).then(response => {
                    let result = response.data;
                    util.dataConvert(this.files,result.data);
                }).catch(err => {
                    this.$notify.error({
                        title:'搜索出错啦',
                        message:err.message
                    })
                });
                this.loading = false;
            },
            handleChildrenData(data){
                util.dataConvert(this.files,data);
            },
            // 返回上一级目录
            backFolder(){
                // 清空选中的数据
                this.checkedFiles = [];
                this.checkAll = false;
                // 查询文件数据
                this.queryAllFiles(util.parentFolderId);
                util.currentFolderId = util.parentFolderId;
                let fid = document.getElementById('changeId');
                fid.value = util.currentFolderId;
                fid.dispatchEvent(new Event('input'));
                let title = document.getElementById('muke-file-title');
                let back = document.getElementById('muke-back-folder');
                if (util.parentFolderId === -1){
                    title.innerHTML =  '全部文件';
                    back.innerHTML = '';
                    // back.innerHTML = '<i class="el-icon-back"/> ';
                    return;

                }
                this.$axios.post(util.API_HOST+'/file/folder/getFolderById',{
                    id:util.parentFolderId
                }).then( response => {
                    let result = response.data;
                    // 填充标题以及文件夹标识
                    if (result.data === null){
                        title.innerHTML =  '全部文件';
                        back.innerHTML = '';
                        return;
                    }
                    this.loading = false;
                    util.parentFolderId = result.data.parentFolderId;
                    title.innerHTML = result.data.folderName;
                }).catch( err => {
                    this.$notify.error({
                        title: err.status,
                        message: err.message
                    });
                });
            },
            // 查询所有文件及文件夹
            queryAllFiles(pid = -1){
                this.$axios.post(util.API_HOST + '/file/folder/query',{pid:pid})
                .then(response => {   
                    let result = response.data;
                    if (result.code === 200){
                        util.dataConvert(this.files,result.data);
                    }
                    this.loading = false;
                }).catch(err => {
                    this.$notify.error({
                        title:err.code,
                        message:err.message
                    })
                    this.loading = false;
                });
                
            },
            // 新增文件夹方法
            newFolder() {
                this.$prompt(
                    '<img src="/static/img/folder.png"/>' , 
                    '新建文件夹', 
                    {
                        dangerouslyUseHTMLString: true,
                        showInput:true,
                        center:true,
                        closeOnClickModal:false,
                        inputPlaceholder:'新文件夹',
                        inputValue:'新建文件夹',
                        confirmButtonText:'新建',
                        showCancelButton:true,
                        inputErrorMessage:'请勿输入非法字符',
                        inputValidator:function(obj){
                            if (obj === ''){
                                return '文件夹名称不能为空';
                            }
                            return !util.validateStr(obj);
                        }
                    }
                ).then(({value})=>{
                    // 新增文件夹
                    console.log(util.currentFolderId);
                    this.$axios.post(util.API_HOST+'/file/folder/add',
                    {
                        name :value,
                        pid:util.currentFolderId
                    }).then(response => {
                        let result = response.data;
                        if (result.code === 200){
                            util.dataConvert(this.files,result.data);
                        } else {
                            this.$message.error('文件夹新增失败');
                        }
                    }).catch(err => {
                        this.$message.error(err.message);
                    })
                });
            },
            // 删除选中的文件
            deleteCheckedFiles(checkedFiles){
                this.$confirm('是否删除选中的文件?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    console.log(checkedFiles);
                    let delDatas = [];
                    for (let file of checkedFiles) {
                        delDatas.push({
                            id:file.id,
                            type:file.type
                        })
                    }
                    // 执行删除请求
                    this.$axios.post(util.API_HOST+'/file/folder/deleteFolders',delDatas)
                    .then(response => {
                        let result = response.data;
                        if (result.code !== 200){
                            return;
                        }
                    }).catch(err => {
                        this.$notify.error({
                            title:"删除错误",
                            message:err.message
                        })
                        return;
                    })
                    // 执行删除操作
                    for (let index = 0; index < checkedFiles.length; index++) {
                        for (let i = 0; i < this.files.length; i++) {
                            if(checkedFiles[index].id===this.files[i].id){
                                this.files.splice(i,1);
                                break;
                            }
                        }
                    }
                    this.checkedFiles = [];
                    this.checkAll = false;
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
                });
            },
            // 打开移动文件对话框
            openMove(checkedFiles) {
                this.moveVisible = true;
            },
            // 目录树懒加载子节点
            loadNode(node, resolve) {
                if(node.level === 0) {
                    let obj = {label:'全部文件',id:-1};
                    resolve([obj]);
                    return;
                } 
                let pid = node.data.id;
                this.$api.post('/file/folder/query/folders',{pid})
                .then(response => {
                    let result = response.data;
                    
                    if(result.code === 200) {
                        for (const file of this.checkedFiles) {
                            result.data.forEach((val,index)=>{
                                if(file.id === val.id){
                                    result.data.splice(index,1);
                                }
                            })
                        }
                        resolve(result.data);
                    }
                }).catch();
            },
            // 点击选择树节点
            selectNode(obj, node, self){
                //console.log(obj);
                this.nodeSelect = true;
                this.selectedFolderName = obj.label;
                this.selectedFolderId = obj.id;

            },
            // 清除树
            clearTree(){
                this.moveVisible = false;
                this.nodeSelect = false;
                this.selectedFolderName = '全部文件';
                this.selectedFolderId = 0;
                this.data = [{label:'全部文件',id:-1}];
            },
            // 保存移动的文件内容
            saveMoveFile(){
                this.loading = true;
                if(this.selectedFolderId === 0){
                    this.loading = false;
                    this.$notify.error('请选择文件夹');
                    return;
                }
                if(this.checkedFiles[0].pid === this.selectedFolderId) {
                    this.loading = false;
                    this.$notify.error('当前文件夹不可移动');
                    return;
                }
                // 组装数据
                let files = [];
                this.checkedFiles.forEach(val => {
                    files.push({id:val.id, type:val.type});
                })

                this.$api.post('/file/folder/save/move/files?folderId=' + this.selectedFolderId,files)
                .then(response => {
                    
                    let result = response.data;
                    if(result.code === 200){
                        this.checkedFiles.forEach(val => {
                            this.files.forEach((file, idx) => {
                                if(val.id === file.id) {
                                    this.files.splice(idx, 1);
                                }
                            })
                        })
                        this.$notify.success({
                            title:'文件移动成功'
                        })
                    } else {
                        this.$notify.error({
                            title:'文件移动失败',
                            message:result.message
                        })
                    }
                    this.loading = false;
                }).catch(error => {
                    this.loading = false;
                    this.$notify.error({
                        title:'文件移动失败',
                        message:error.message
                    })
                });

            },
            showListStyle() {
                this.isShow = false;
            },
            showGridStyle() {
                this.isShow = true;
            },
            handleCheckAllChange(val) {
                this.checkedFiles = [];
                let currentFiles = [];
                if(val){
                    this.files.forEach(function(o,i){
                        currentFiles.push(o);
                    });
                    this.checkedFiles = currentFiles;
                }
                this.checkAll = val;
            },
            handleCheckedFilesChange(value) {
                let checkedCount = value.length;
                this.checkAll = checkedCount === this.files.length;
                this.isIndeterminate = checkedCount > 0 && checkedCount < this.files.length;
            },
            handleCommand(command) {
                // this.$message('click on item ' + command);
                if (command === 'file'){
                    $('#upload-btn').click();
                    // 显示上传列表
                    document.getElementById('upload-component').style.display = 'block';
                }
            }
        },
        data(){
            // 返回数据
            return{
                icon2:'el-icon-folder',
                // 表单验证规则
                rules:{
                    name:[
                        { required: true, message: '请输入分享名称', trigger: 'blur' },
                        { min: 1, max: 20, message: '长度在 1 到 20个字符', trigger: 'blur' }
                    ],
                    validTime:[
                        { required: true, message: '请选择有效期', trigger: 'blur' }
                    ]
                },
                share: {
                    name: '',
                    validTime: '7'
                },
                formLabelWidth: '80px',
                timer: null,
                drawer: false,
                direction: 'rtl',
                files:[
                    {id:1,name:'aaaaa',fileSize:'---',type:'folder',updateTime:'2021-02-20'},
                    {id:2,name:'aaaaaaa.docx',fileSize:'10MB',type:'file',fileType:'docx',updateTime:'2021-02-20'},
                    {id:3,name:'Spring5.pdf',fileSize:'14MB',type:'file',fileType:'pdf',updateTime:'2021-02-20'},
                    {id:4,name:'aaaaa.xlsx',fileSize:'1.2MB',type:'file',fileType:'xlsx',updateTime:'2021-02-20'},
                    {id:5,name:'aaaaa.ttt',fileSize:'1.5MB',type:'file',fileType:'ttt',updateTime:'2021-02-20'},
                    {id:6,name:'aaaaa.ppt',fileSize:'23MB',type:'file',fileType:'ppt',updateTime:'2021-02-20'},
                    {id:7,name:'aaaaa.rar',fileSize:'145MB',type:'file',fileType:'rar',updateTime:'2021-02-20'},
                    {id:8,name:'aaaaa.zip',fileSize:'340MB',type:'file',fileType:'zip',updateTime:'2021-02-20'},
                    {id:9,name:'aaaaa.html',fileSize:'1.2MB',type:'file',fileType:'html',updateTime:'2021-02-20'},
                    {id:10,name:'aaaaa.txt',fileSize:'108KB',type:'file',fileType:'txt',updateTime:'2021-02-20'}
                ],
                loading:true,
                filename:'',
                isShow:false,
                checkAll: false,
                checkedFiles:[],
                shareUrl:{
                    url:'',
                    code:''
                },
                createLoading:false,
                dialogFormVisible:false,
                moveVisible:false,
                data: [{
                    label: '全部文件',
                    children: [{
                        label: '一级 1',
                        children: [{
                            label: '二级 1-1'
                        }]
                    }, {
                        label: '一级 2',
                    }, {
                        label: '一级 3',
                    }, {
                        label: '一级 4',
                    }, {
                        label: '一级 5',
                    }, {
                        label: '一级 6',
                    }, {
                        label: '一级 7',
                    }]
                }],
                nodeSelect:false,
                selectedFolderName:'全部文件',
                selectedFolderId:0,
            }
        }
    }
</script>

<style scoped>
    .drawer-content{
        margin: 30px;
    }
    .drawer-footer{
        margin-left: 80px;
    }
    
    #muke-right{
        /* min-height: 500px; */
        float: left;
        /* width: 100%; */
        height: 100vh;
        position: absolute;
        left: 320px; right: 0px;
    }
    #muke-right-content{
        /* min-width: max-content; */
        max-height: 100%;
        margin: 20px 20px 0px 20px;
        
    }
    #searchboxMuke{
        width: 240px;
    }
    #muke-file-content{
        overflow: scroll;
        width: 100%;
        min-width: max-content;
        /* min-width: 980px; */
        max-height: 63vh;
        min-height: max-content;
        /* max-width: 980px; */
        margin: 20px 0px 0px 0px;
        border-bottom: 1px solid gainsboro;
    }
    .muke-file-edit-block{
        float: right;
        margin: 10px 10px 0px 0px;
    }
    .muke-file-edit-left{
        float: left;
        margin: 10px 10px 0px 0px;
    }
    .muke-file-edit-left span{
        padding-top: 10px;
        font-size: 16px;
        line-height: 36px;
        font-family: Poppins;
        font-weight: 700;
        
    }
    #muke-file-show-icon{
        padding-top: 10px;padding-right: 10px;
        height: 30px;
    }
    .muke-file-show{
        float: right;
        padding: 4px;border-radius: 4px;
        width: 30px; height: 30px;
    }
    .muke-file-show:hover{
        background-color: #EBEEF5;
        cursor: pointer;
    }
    #list-icon{
        width: 22px; height: 22px;
    }
    #header-checkbox,#header-name,#header-size,#header-date{
        float: left;font-family: Poppins;
        font-size: 18px;
    }
    #header-checkbox{width: 30px;}
    #header-name{
        width: 45%;margin:0px 5px; font-size: 15px;
        min-width: max-content;
    }
    #header-size{
        width: 25%;font-size: 15px;
        min-width: max-content;
    }
    #header-date{
        width: 20%;font-size: 15px;
        min-width: max-content;
    }
    /* #header-date{} */
    #muke-file-count{
        float: left;
        line-height: 30px;padding: 10px 10px 0px 0px;
    }
    #muke-back-folder{
        cursor: pointer;
    }
    #muke-back-folder:hover{color: rgb(32, 156, 228);}

    #file-tree{
        border-radius: 5px;
        width: 100%;
        height: 200px;
        overflow: auto;
        border: 1px solid rgba(161, 157, 157, 0.411);
    }
</style>